#include "ConfigLocal.h"

#include <fstream>
#include <sstream>

#include <core/FileSys.h>

#include "../UserAccountManager.h"

ConfigLocal::~ConfigLocal() { SaveContent(); }

void ConfigLocal::SetConfig(const char* key, const char* value) {
  LoadContent();
  m_config[key] = value;
}

void ConfigLocal::SetConfig(const char* key, int value) {
  LoadContent();
  m_config[key] = std::to_string(value);
}

void ConfigLocal::SetConfig(const char* key, bool value, int precise) {
  LoadContent();
  std::ostringstream out;
  out.precision(precise);
  out.flags(std::ios::fixed);
  m_config[key] = out.str();
}

std::string ConfigLocal::GetConfig(const char* key) {
  LoadContent();
  if (!m_config.isMember(key)) return "";
  return m_config[key].asString();
}

ConfigLocal::ConfigLocal() {}

void ConfigLocal::LoadContent() {
  if (m_load) return;

  m_load = true;
  QString strAppPath = FileSys::instance()->writeableAppCfgDir();
  strAppPath.append(SSUserAccountManager::instance().GetUserInfo().m_UserId);
  strAppPath.append(".json");
  m_path = strAppPath.toStdString();
  std::string sJson;
  LoadLocalFile(m_path, sJson);
  Json::Reader js_reader;
  if (!js_reader.parse(sJson, m_config)) return;
}

void ConfigLocal::SaveContent() {
  if (!m_load) return;

  QString strAppPath = FileSys::instance()->writeableAppCfgDir();
  FileSys::instance()->makePathExist(strAppPath);

  SaveLocalFile(m_path, m_config.toStyledString());
  m_load = false;
  m_config.clear();
}

void ConfigLocal::LoadLocalFile(const std::string& sPath, std::string& sValue) {
  std::ifstream ifs;
  ifs.open(sPath.c_str(), std::ios::in);

  if (!ifs.is_open()) return;

  std::stringstream ssBuffer;

  ssBuffer << ifs.rdbuf();

  sValue = ssBuffer.str();

  ifs.close();
}

void ConfigLocal::SaveLocalFile(const std::string& sPath, std::string sValue) {
  std::ofstream ofs;
  ofs.open(sPath.c_str(), std::ios::out);

  if (!ofs.is_open()) return;

  ofs << sValue;
  ofs.close();
}